import { useQuasar } from '@teld/q-components';
import Icon from '@teld/q-components/Icon';
import Component from '@teld/q-components/Input';
import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import { computed, defineComponent, onMounted, ref, watch } from 'vue';
import LabelPrefixWraper from '../label-prefix-wraper';
import styles from './index.module.scss';
import './index.scss';
import useMark ,{sysHasMaskAuth}from 't/common/hooks/useMask';
export * from '@teld/q-components/Input';

export default defineComponent({
  name: fixNameSpace(Component.name),
  props: {
    ...commonProps,
    ...Component.props,
    ...LabelPrefixWraper.props,
    prependIcon: {
      type: String,
    },
    appendIcon: {
      type: String,
    },
    label: {
      type: String,
      default() {
        return '';
      },
    },
    placeholder: {
      type: String,
      default() {
        return '';
      },
    },
    bgColor: {
      type: String,
      default() {
        return '#ffffff';
      },
    },
    // clearTrigger: {
    //   type: String,
    //   default() {
    //     return 'focus';
    //   },
    // },
    dense: {
      type: Boolean,
      default() {
        return true;
      },
    },
    showClearButton: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    borderless: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    outlined: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    filled: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    maxLength: {
      type: Number,
    },
    borderType: {
      type: String,
      default() {
        return 'borderless';
      },
      maxHeight: String,
      maxWidth: String,


    },
    enableMask: {
      type: Boolean,
      default() {
        return false;
      },
    },
    value_mask: String
  },
  emits: ['focus', 'change', 'validate', 'blur', 'click', 'keydown'],

  setup(props, { attrs, emit, expose, slots }) {
    const $q = useQuasar();
    const maskValue = ref('')
    const isMasked = ref(true)
    const IsMasked = computed(() => {
      return isMasked.value
    })
    const refComponent = ref();
    const [mappingProps, mappingExpose] = useMappingProps(props, {
      clear() {
        refComponent.value.clear(...arguments);
      },
      validate() {
        return refComponent.value.validate(...arguments);
      },
      update() {
        return refComponent.value.update(...arguments);
      },
      resetValidation() {
        refComponent.value.resetValidation(...arguments);
      },
      blur() {
        refComponent.value.blur(...arguments);
      },
      focus() {
        refComponent.value.focus(...arguments);
      },
      showMask: (val) => {
        if(!sysHasMaskAuth()||!props.enableMask) return
        isMasked.value = val
      },
      ShowMask: (val) => {
        if(!sysHasMaskAuth()||!props.enableMask) return
        isMasked.value = val
      },
      IsMasked,
      isMasked:IsMasked
    });
    const { initMask, maskIconClick } = useMark(mappingProps, '', isMasked)



    expose(mappingExpose);

    onMounted(() => { });

    let clearable = computed(() => {
      return mappingProps.showClearButton ?? mappingProps.clearable;
    });
    let labelPosition = computed(() => {
      if ($q.platform.is.mobile) {
        return 'top';
      }
      return mappingProps.labelPosition;
    });
    // let maxlength = computed(() => {
    //   let ml = mappingProps.maxLength || mappingProps.maxlength;
    //   return {
    //     counter: mappingProps.counter || !!ml,
    //     maxlength: ml,
    //   };
    // });
    let disable = computed(() => {
      let db = mappingProps.disable || mappingProps.disabled;
      let shouldSetBgColor = db;
      return {
        bgColor: shouldSetBgColor ? '#f1f1f1' : mappingProps.bgColor,
        disable: db,
      };
    });
    function onClick(params,e) {
      emit('click', e);
    }
    function onBlur(e) {
      emit('blur', e);
    }
    function onChange(e) {
      emit('change', e);
    }
    function onKeydown(e) {
      emit('keydown', e); 
    }
    let proxyModelValue = ref('')

    watch(() => [mappingProps.readonly, mappingProps.disabled, isMasked.value, mappingProps.modelValue, mappingProps.value_mask], () => {
      if (isMasked.value&&mappingProps.readonly&&mappingProps.enableMask) {
        proxyModelValue.value = mappingProps.value_mask
      } else {
        proxyModelValue.value = mappingProps.modelValue
      }
    }, {
      immediate: true
    })
    watch(() => proxyModelValue.value, () => {
      if (!isMasked.value||!mappingProps.readonly) {
        mappingProps.modelValue = proxyModelValue.value
      }
    })
    return () => {
      let Type;
      if (mappingProps?.borderType) {
        Type = Object.fromEntries(
          ['outlined', 'standout', 'filled', 'borderless'].map(k => {
            return [k, mappingProps[k] ?? mappingProps.borderType === k];
          }),
        );
      } else {
        Type = { borderless: true };
      }


      //=============去除内部hover时虚线边框========
      let attrs_ = { ...attrs };
      delete attrs_['data-uid'];
      delete attrs_['data-tag'];
      delete attrs_['class'];
      delete attrs_['style'];
      return (
        <div
          class={[
            'tr-input-default',
            labelPosition.value == 'top' && 'tr-input-default-top',
            (mappingProps.requiredMessage || mappingProps.maxLength) &&
            'tr-input-requiredmessage',
            mappingProps.borderType == 'standout' && 't-input-standard',
            mappingProps.readonly && 'tr-input-readonly',
            (mappingProps.disable || mappingProps.disabled) &&
            'tr-input-disabled',
          ]}
          v-show={mappingProps.visible}
          {...attrs}
          tabindex='-1'
        >
          <LabelPrefixWraper
            required={mappingProps.required}
            label={mappingProps.label}
            labelProps={{ class: 'input-title' }}
            hideLabel={mappingProps.hideLabel}
            labelType='input'
            labelPosition={labelPosition.value}
            helpConf={mappingProps.helpConf}
            readonly={mappingProps.readonly}
            helpTooltip={mappingProps.helpTooltip}
            helpPlacement={mappingProps.helpPlacement}
            helpMore={mappingProps.helpMore}
            maxHeight={mappingProps.maxHeight}
            maxWidth={mappingProps.maxWidth}
            helpMorePopup={mappingProps.helpMorePopup}
            helpMoreLink={mappingProps.helpMoreLink}
            helpMoreLinkHrefStatic={mappingProps.helpMoreLinkHrefStatic}
            helpMoreLinkHrefExp={mappingProps.helpMoreLinkHrefExp}
          ></LabelPrefixWraper>
          <Component
            ref={refComponent}
            class={['t-input', styles.module]}
            {...attrs_}
            {...pickOwnForBasicComponent(mappingProps, Component.props, attrs_)}
            label={undefined}
            {...Type}
            maxlength={mappingProps.maxLength}
            prefix={props.prefix ? props.prefix : null}
            suffix={props.suffix ? props.suffix : null}
            {...disable.value}
            clearable={clearable.value}
            placeholder={mappingProps.placeholder || attrs.placeholder}
            onClick={onClick}
            onKeydown={onKeydown}
            onUpdate:modelValue={onChange}
            onBlur={onBlur}
            tabindex={mappingProps.tabIndex ? mappingProps.tabIndex : 1}
            modelValue={proxyModelValue.value}

            // v-slots={{ ...slots }}
            v-slots={{
              ...slots,

              prepend: mappingProps.prependIcon
                ? () => {
                  let t = mappingProps.prependIcon;
                  return t ? (
                    <Icon class={[t]} name={t}></Icon>
                  ) : (
                    slots.prepend?.()
                  );
                }
                : slots.prepend,

              append: () => {
                if(slots.append){
                  return slots.append?.()
                }
                if (mappingProps.readonly) {
                  if (initMask()&&sysHasMaskAuth()) {
                    return (
                      <span class='fas-label-mask custom'>
                        <i
                          class={
                            !isMasked.value
                              ? 'dx-icon fas icon-t-mask-open'
                              : 'dx-icon fas icon-t-mask-close'
                          }
                          style={'font-size:14px'}
                          onClick={maskIconClick}
                        ></i>
                      </span>
                    );
                  }
                  return ''
                };
                if (mappingProps.appendIcon) {
                  return <Icon class={[mappingProps.appendIcon]} name={mappingProps.appendIcon}></Icon>
                }
                return slots.append?.()
              }
            }}
            onFocus={e => {
              emit('focus', e);
            }}
          ></Component>
        </div>
      );
    };
  },
});
